package com.ruoyi.web.controller.system;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.SysProvidecontractdetails;
import com.ruoyi.system.domain.SysPurchasingunit;
import com.ruoyi.system.domain.SysSupplier;
import com.ruoyi.system.service.ISysProvidecontractdetailsService;
import com.ruoyi.system.service.ISysPurchasingunitService;
import com.ruoyi.system.service.ISysSupplierService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysProvidecontract;
import com.ruoyi.system.service.ISysProvidecontractService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 供货合同实体Controller
 * 
 * @author ruoyi
 * @date 2020-12-13
 */
@Controller
@RequestMapping("/system/providecontract")
public class SysProvidecontractController extends BaseController {
    private String prefix = "system/providecontract";

    @Autowired
    private ISysProvidecontractService sysProvidecontractService;
    @Autowired
    private ISysSupplierService sysSupplierService;
    @Autowired
    private ISysPurchasingunitService sysPurchasingunitService;
    @Autowired
    private ISysProvidecontractdetailsService sysProvidecontractdetailsService;

    @RequiresPermissions("system:providecontract:view")
    @GetMapping()
    public String providecontract() {
        return prefix + "/providecontract";
    }

    /**
     * 查询供货合同实体列表
     */
    @RequiresPermissions("system:providecontract:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysProvidecontract sysProvidecontract) {
        startPage();
        SysUser sysUser=ShiroUtils.getSysUser();
        if(sysUser.getUserType().equals("11")){
            sysProvidecontract.setSupplierId(sysUser.getCompanyId());
        }else if(sysUser.getUserType().equals("10")){
            sysProvidecontract.setPurchasingUnitId(sysUser.getCompanyId());
        }
        List<SysProvidecontract> list = sysProvidecontractService.selectSysProvidecontractList(sysProvidecontract);
        return getDataTable(list);
    }

    /**
     * 导出供货合同实体列表
     */
    @RequiresPermissions("system:providecontract:export")
    @Log(title = "供货合同实体", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysProvidecontract sysProvidecontract) {
        SysUser sysUser=ShiroUtils.getSysUser();
        if(sysUser.getUserType().equals("11")){
            sysProvidecontract.setSupplierId(sysUser.getCompanyId());
        }else if(sysUser.getUserType().equals("10")){
            sysProvidecontract.setPurchasingUnitId(sysUser.getCompanyId());
        }
        List<SysProvidecontract> list = sysProvidecontractService.selectSysProvidecontractList(sysProvidecontract);
        ExcelUtil<SysProvidecontract> util = new ExcelUtil<SysProvidecontract>(SysProvidecontract.class);
        return util.exportExcel(list, "providecontract");
    }

    /**
     * 新增供货合同实体
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        List<SysSupplier> suppliers = sysSupplierService.selectSysSupplierList(null);
        List<SysPurchasingunit> sysPurchasingunits = sysPurchasingunitService.selectSysPurchasingunitList(null);
        SysUser sysUser=ShiroUtils.getSysUser();
        if(sysUser.getUserType().equals("11")){
            SysSupplier sysSupplier=sysSupplierService.selectSysSupplierById(sysUser.getCompanyId());
            mmap.put("supplier", sysSupplier);
        }

        mmap.put("suppliers", suppliers);
        mmap.put("sysPurchasingunits", sysPurchasingunits);
        return prefix + "/add";
    }

    /**
     * 新增保存供货合同实体
     */
    @RequiresPermissions("system:providecontract:add")
    @Log(title = "供货合同实体", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysProvidecontract sysProvidecontract) {
        // 0未使用 1 已使用
        sysProvidecontract.setStatus("0");
        Calendar calendar=Calendar.getInstance();
        String year=calendar.get(Calendar.YEAR)+"";
        String contractNumber = "";
        List<SysProvidecontract> pList=sysProvidecontractService.findContractNumber(year);
        if(pList.size()>0 && pList!=null){
            String[] biggerNumber = pList.get(pList.size() - 1).getContractNumber().split("-");
            int contractNum = Integer.parseInt(biggerNumber[1]);
            //判断有没有断号
            if(pList.size() != contractNum){
                //循环找出被删掉的第一个号
                int number = 0;
                //从第一个开始，取出编号，与累加数i+1不相等的即为空缺编号
                for(int i = 0; i < pList.size(); i++){
                    String[] tempNumber = pList.get(i).getContractNumber().split("-");
                    if((i + 1) != Integer.parseInt(tempNumber[1])){
                        number = i + 1;
                        break;
                    }

                }
                //生成编号
                contractNumber = year + "-" + number;
            }
            else{
                //用最大的生成编号
                contractNumber = year + "-" + (Integer.parseInt(biggerNumber[1]) + 1);
            }
        }
        else{
            //第一条记录默认编号从1开始
            contractNumber = year + "-1";
        }
        sysProvidecontract.setContractNumber(contractNumber);

        SysUser sysUser= ShiroUtils.getSysUser();
        sysProvidecontract.setSupplierId(sysUser.getCompanyId());
        sysProvidecontract.setAttribite1(sysUser.getUserName());//供应商名称
        return toAjax(sysProvidecontractService.insertSysProvidecontract(sysProvidecontract));
    }

    /**
     * 修改供货合同实体
     */
    @GetMapping("/edit/{provideContractId}")
    public String edit(@PathVariable("provideContractId") Long provideContractId, ModelMap mmap) {
        SysProvidecontract sysProvidecontract = sysProvidecontractService.selectSysProvidecontractById(provideContractId);
        List<SysSupplier> suppliers = sysSupplierService.selectSysSupplierList(null);
        List<SysPurchasingunit> sysPurchasingunits = sysPurchasingunitService.selectSysPurchasingunitList(null);
        mmap.put("suppliers", suppliers);
        mmap.put("sysPurchasingunits", sysPurchasingunits);
        mmap.put("sysProvidecontract", sysProvidecontract);
        return prefix + "/edit";
    }

    /**
     * 修改保存供货合同实体
     */
    @RequiresPermissions("system:providecontract:edit")
    @Log(title = "供货合同实体", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysProvidecontract sysProvidecontract) {
        return toAjax(sysProvidecontractService.updateSysProvidecontract(sysProvidecontract));
    }

    /**
     * 删除供货合同实体
     */
    @RequiresPermissions("system:providecontract:remove")
    @Log(title = "供货合同实体", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(sysProvidecontractService.deleteSysProvidecontractByIds(ids));
    }

    /**
     * 供货合同预览
     *
     * @param mmap
     * @param provideContractId
     * @return
     */
    @Log(title = "供货合同预览", businessType = BusinessType.EXPORT)
    @GetMapping("/preview")
    public String previewContract(ModelMap mmap, String provideContractId) {
//        if(null == request.getSession().getAttribute("supplier")){
//            return "redirect:sessionOutNoResponseBody.action";
//        }
//
//        Map<String,Object> condition = new HashMap<String,Object>();
//        condition.put("provideContractId", provideContractId);
//
//        ProvideContract provideContract = provideContractServiceImpl.fetch(provideContractId);

        SysProvidecontract provideContract = sysProvidecontractService.selectSysProvidecontractById(Long.parseLong(provideContractId));
        SysProvidecontractdetails sd = new SysProvidecontractdetails();
        sd.setProvideContractId(provideContract.getProvideContractId());
        List<SysProvidecontractdetails> listDetails = sysProvidecontractdetailsService.selectSysProvidecontractdetailsList(sd);

        //计算总价
        double number = 0L;
        double price, sumPrice = 0;
        DecimalFormat df = new DecimalFormat("#.00");
        if (listDetails.size() > 0 && listDetails != null) {
            for (int i = 0; i < listDetails.size(); i++) {
                number = listDetails.get(i).getNumber();
                price = listDetails.get(i).getDealPrice();
                if(listDetails.get(i).getAttribite1()!=null&&listDetails.get(i).getAttribite1().indexOf(",")>0){
                    listDetails.get(i).setAtrs(listDetails.get(i).getAttribite1().split(","));
                }
                double temp = number * price;
                String strSum = df.format(temp);
                strSum = strSum.replace(".", "");
                String sum = "";
                for (int j = 0; j < strSum.length(); j++) {
                    if (j + 1 < strSum.length()) {
                        sum += strSum.substring(j, j + 1) + ",";
                    } else {
                        sum += strSum.substring(j, j + 1);
                    }
                }
                sumPrice += number * price;
                //补全
                for (int k = 0; k < 9 - strSum.length(); k++) {
                    sum = " ," + sum;
                }
                listDetails.get(i).setAttribite1(sum);
            }
        }

        String dfSumPrice = df.format(sumPrice);
        dfSumPrice = dfSumPrice.replace(".", "");
        String strSumPrice = "";
        for (int n = 0; n < dfSumPrice.length(); n++) {
            if (n + 1 < dfSumPrice.length()) {
                strSumPrice += dfSumPrice.substring(n, n + 1) + ",";
            } else {
                strSumPrice += dfSumPrice.substring(n, n + 1);
            }
        }

        for (int m = 0; m < 9 - dfSumPrice.length(); m++) {
            strSumPrice = " ," + strSumPrice;
        }
        mmap.put("prices",strSumPrice.split(","));
        mmap.put("provideContract", provideContract);
        mmap.put("listDetails", listDetails);
        return prefix + "/view";

    }
}
